﻿using System;
using System.Linq;
using System.Web.UI.WebControls;
using Data.Entity;
using Service;
using System.Collections.Generic;

namespace ECommerce.Administration.Controls
{
	public partial class RelatedProducts : AdminBaseUsercontrol
	{
		private int _ProductID;
		private IRelatedProductService _RelatedProductService;
		private IProductService _ProductService;
		private IEnumerable<Product> _DataSource;
		private int _TotalRecords;

		public int PageIndex
		{
			get
			{
				if (ViewState["PageIndex"] == null)
				{
					return 0;
				}
				else
				{
					return int.Parse(ViewState["PageIndex"].ToString());
				}
			}
			set
			{
				ViewState["PageIndex"] = value;
			}
		}

		public int TotalRecords
		{
			get
			{
				return _TotalRecords;
			}
			set
			{
				_TotalRecords = value;
			}
		}

		public int TotalPages
		{
			get
			{
				var data = DataSource;

				if (data == null)
				{
					return 0;
				}

				int totalRecords = TotalRecords;

				int totalPages = 0;

				if (totalRecords <= PageSize)
				{
					totalPages = 1;
				}

				if (totalRecords % PageSize == 0)
				{
					totalPages = totalRecords / PageSize;
				}

				if (totalRecords % PageSize > 0)
				{
					totalPages = totalRecords / PageSize + 1;
				}

				return totalPages;
			}
		}

		public int PageSize
		{
			get
			{
				return this.GridProducts.PageSize;
			}
			set
			{
				this.GridProducts.PageSize = value;
			}
		}

		public IEnumerable<Product> DataSource
		{
			get
			{
				var pageIndex = this.PageIndex;
				var totalRecords = 0;
				var pageSize = this.PageSize;

				if (_ProductService == null)
				{
					_ProductService = new ProductService();
				}
				
				if (SiteContext.Current.WorkingLanguage == null)
				{
					this.TotalRecords = 0;
					return null;
				}

				int currentLanguageID = SiteContext.Current.WorkingLanguage.LanguageId;

				_DataSource = _ProductService.GetProductsByLanguage(currentLanguageID, pageIndex, pageSize, out totalRecords);

				if (_DataSource != null)
				{
					_DataSource = _DataSource.Where(exp => exp.ProductID != this.ProductID);
				}

				this.TotalRecords = totalRecords;

				return _DataSource;
			}
		}

		public int ProductID
		{
			get
			{
				if (ViewState["ProductID"] != null)
				{
					_ProductID = (int)ViewState["ProductID"];

					return _ProductID;
				}

				_ProductID = CommonHelper.QueryStringInt("productID");
				return _ProductID;
			}
			set
			{
				ViewState["ProductID"] = value;
				_ProductID = value;
			}
		}

		protected void GridRelatedProducts_RowUpdating(object sender, GridViewUpdateEventArgs e)
		{
			int relatedProductId = (int)GridRelatedProducts.DataKeys[e.RowIndex]["RelatedProductID"];
			int ProductID2 = (int)GridRelatedProducts.DataKeys[e.RowIndex]["ProductID2"];
			var TextDisplayOrder = GridRelatedProducts.Rows[e.RowIndex].FindControl("TextDisplayOrder") as TextBox;
			int displayOrder = 0;
			if (int.TryParse(TextDisplayOrder.Text.Trim(), out displayOrder))
			{
				var theRelatedProduct = new RelatedProduct();

				theRelatedProduct.DisplayOrder = displayOrder;
				theRelatedProduct.ProductID1 = ProductID;
				theRelatedProduct.ProductID2 = ProductID2;
				theRelatedProduct.RelatedProductID = relatedProductId;

				if (_RelatedProductService == null)
				{
					_RelatedProductService = new RelatedProductService();
				}

				_RelatedProductService.UpdateRelatedProduct(theRelatedProduct);
			}
		}

		protected void GridProducts_PageIndexChanging(object sender, GridViewPageEventArgs e)
		{
			GridProducts.PageIndex = e.NewPageIndex;
		}

		protected void GridProducts_RowDataBound(object sender, GridViewRowEventArgs e)
		{
			if (e.Row.RowType == DataControlRowType.Header)
			{
				e.Row.Cells[1].Text = GetLocalResourceString("Admin.ProductList.NameHeader");
				e.Row.Cells[2].Text = GetLocalResourceString("Admin.ProductList.ListPriceHeader");
			}
		}

		protected void LinkButtonPaging_Command(object sender, System.Web.UI.WebControls.CommandEventArgs e)
		{
			switch (e.CommandName)
			{
				case "FirstPage":
					{
						PageIndex = 0;

						BindProducts();
					}
					break;
				case "PageIndex":
					{
						LinkButton theLink = sender as LinkButton;

						int index = int.Parse(theLink.Text);

						PageIndex = index - 1;

						BindProducts();
					}
					break;
				case "LastPage":
					{
						PageIndex = TotalPages - 1;

						BindProducts();
					}
					break;
			}
		}
		
		private void BindProducts()
		{
			var data = DataSource;

			if (data != null)
			{
				data = data.OrderByDescending(exp => exp.CreatedOn);
			}

			GridProducts.DataSource = data;
			GridProducts.DataBind();
		}

		protected void Page_Load(object sender, EventArgs e)
		{
			if (SiteContext.Current == null)
			{
				Server.Transfer("~Administration/AdminLogin.aspx");
			}

			if (!IsPostBack)
			{
				ButtonAdd.Text = GetLocalResourceString("Admin.AddButtonText");
				ButtonCancel.Text = GetLocalResourceString("ECommerce.CancelButtonText");
				ButtonAddNewRelatedProd.Text = GetLocalResourceString("Admin.AddNewRelatedProduct_ButtonText");
			}
		}

		protected void Page_PreRender(object sender, EventArgs e)
		{
			if (ProductID > 0)
			{
				PanelMain.Visible = true;
				pnlMessage.Visible = false;

				BindRelatedProducts();
				BindProducts();

				var currentPageIndex = this.PageIndex;
				var totalPages = TotalPages;

				if (currentPageIndex == 0 || PageSize <= 1)
				{
					LinkButtonFirstPage.Enabled = false;
				}
				else
				{
					LinkButtonFirstPage.Enabled = true;
				}

				if (currentPageIndex == totalPages - 1 || totalPages <= 1)
				{
					LinkButtonLastPage.Enabled = false;
				}
				else
				{
					LinkButtonLastPage.Enabled = true;
				}

				// set pager index links
				List<PagerIndex> indexs = new List<PagerIndex>();

				if (totalPages <= 10)
				{
					for (int i = 1; i <= totalPages; i++)
					{
						indexs.Add(new PagerIndex(i.ToString()));
					}
				}
				else if (totalPages > 10)
				{
					if (((currentPageIndex / 10) * 10 + 10) > totalPages)
					{
						for (int i = (currentPageIndex / 10) * 10 + 1; i <= totalPages; i++)
						{
							indexs.Add(new PagerIndex(i.ToString()));
						}
					}
					else if (((currentPageIndex / 10) * 10 + 10) <= totalPages)
					{
						for (int i = (currentPageIndex / 10) * 10 + 1; i <= (currentPageIndex / 10) * 10 + 10; i++)
						{
							indexs.Add(new PagerIndex(i.ToString()));
						}
					}
				}

				this.RepeaterPageIndex.DataSource = indexs;
				this.RepeaterPageIndex.DataBind();

				// disenabel the current pagerindex link
				if (RepeaterPageIndex.TemplateControl.Controls.Count > 1)
				{
					for (int i = 0; i < RepeaterPageIndex.Items.Count; i++)
					{
						LinkButton thePagerIndexLink = RepeaterPageIndex.Items[i].FindControl("LinkButtonPageIndex") as LinkButton;

						if (thePagerIndexLink.Text.Equals((currentPageIndex + 1).ToString()))
						{
							thePagerIndexLink.Enabled = false;
						}
					}
				}
			}
			else
			{
				PanelMain.Visible = false;
				pnlMessage.Visible = true;
			}
		}

		protected void ButtonAdd_Click(object sender, EventArgs e)
		{
			if (_RelatedProductService == null)
			{
				_RelatedProductService = new RelatedProductService();
			}

			foreach (GridViewRow row in GridProducts.Rows)
			{
				var cbProduct = row.FindControl("cbProduct") as CheckBox;

				if (cbProduct.Checked)
				{
					var hfProductId = row.FindControl("hfProductId") as HiddenField;
					int theProdID = int.Parse(hfProductId.Value);

					if (ProductID != theProdID)
					{
						var theNewRelatedProd = new Data.Entity.RelatedProduct();

						theNewRelatedProd.DisplayOrder = 0;
						theNewRelatedProd.ProductID1 = ProductID;
						theNewRelatedProd.ProductID2 = theProdID;

						_RelatedProductService.CreateNewRelatedProduct(theNewRelatedProd);
					}
				}
			}
		}

		protected void GridRelatedProducts_RowDeleting(object sender, GridViewDeleteEventArgs e)
		{
			if (_RelatedProductService == null)
			{
				_RelatedProductService = new RelatedProductService();
			}

			int relatedProductId = (int)GridRelatedProducts.DataKeys[e.RowIndex]["ProductID2"];

			_RelatedProductService.DeleteRelatedProduct(ProductID, relatedProductId);
		}

		protected void GridRelatedProducts_RowDataBound(object sender, GridViewRowEventArgs e)
		{
			if (e.Row.RowType == DataControlRowType.Header)
			{
				e.Row.Cells[0].Text = GetLocalResourceString("Admin.ProductList.NameHeader");
				e.Row.Cells[1].Text = GetLocalResourceString("Admin.ProductList.ListPriceHeader");
				e.Row.Cells[2].Text = GetLocalResourceString("Admin.ProductList.DisplayOrderHeader");
			}

			if (e.Row.DataItem != null)
			{
				var LinkButtonDelete = e.Row.FindControl("LinkButtonDelete") as LinkButton;
				var ButtonUpdate = e.Row.FindControl("ButtonUpdate") as Button;

				ButtonUpdate.Text = GetLocalResourceString("Admin.UpdateButtonText");
				LinkButtonDelete.Text = GetLocalResourceString("Admin.DeleteButtonText");
			}
		}

		private void BindRelatedProducts()
		{
			if (ProductID > 0 && SiteContext.Current.WorkingLanguage != null)
			{
				if (_RelatedProductService == null)
				{
					_RelatedProductService = new RelatedProductService();
				}

				if (_ProductService == null)
				{
					_ProductService = new ProductService();
				}

				var relatedProducts = _RelatedProductService.GetRelatedProducts(ProductID);

				if (relatedProducts != null)
				{
					var products = _ProductService.GetAllProductsByLanguage(SiteContext.Current.WorkingLanguage.LanguageId);

					var data = (from rp in relatedProducts
								join p in products on rp.ProductID2 equals p.ProductID
								select new
								{
									ProductName = p.Name,
									ListPrice = p.ListPrice,
									ProductID2 = rp.ProductID2,
									ProductID1 = rp.ProductID1,
									DisplayOrder = rp.DisplayOrder,
									RelatedProductID = rp.RelatedProductID
								});

					GridRelatedProducts.DataSource = data;
					GridRelatedProducts.DataBind();
				}
			}
		}
	}
}